<template>
    <el-card class="profile-card">
        <template #header>
            <div class="card-header">
                <el-icon>
                    <User />
                </el-icon>
                <span style="margin-left: 8px;">个人中心</span>
            </div>
        </template>

        <div class="profile-content">
            <div class="avatar-section">
                <el-avatar :size="100"
                    :src="profile.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2649a9be4292c60jpeg.jpeg'"
                    fit="cover">
                    <img v-if="!profile.avatarUrl" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2649a9be4292c60jpeg.jpeg" />
                </el-avatar>
                <el-upload class="avatar-uploader" action="#" :show-file-list="false" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload" :http-request="uploadAvatar">
                    <el-button type="link" size="small" class="change-avatar-button">更换头像</el-button>
                </el-upload>
            </div>

            <el-form :model="profile" label-width="80px" class="profile-form">
                <el-form-item label="用户名">
                    <el-input v-model="profile.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="profile.name"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="profile.email"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="profile.phone"></el-input>
                </el-form-item>
                <el-form-item label="部门">
                    <el-input v-model="profile.department"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveProfile">保存</el-button>
                </el-form-item>
                </el-form>
        </div>
    </el-card>
</template>

<script setup>
import { useAuthStore } from '../../stores/authStore';
import { Camera, User } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import personalInfoService from '../../services/personalInfoService';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';

const authStore = useAuthStore();
const router = useRouter();

const profile = ref({
    name: '',
    username: '',
    email: '',
    phone: '',
    department: '',
    avatarUrl: ''
});

/**
 * 获取用户个人信息
 */
const fetchProfile = async () => {
    console.log('>>> 尝试获取个人信息...');
    try {
        const profileData = await personalInfoService.getPersonalInfo();
        profile.value = profileData;
        // 【关键修改】: 将获取到的头像URL同步到authStore中
        if (profileData.avatarUrl && authStore.user) {
            authStore.user.avatar = profileData.avatarUrl;
            // 同时更新 localStorage 中的用户数据
            localStorage.setItem('user', JSON.stringify(authStore.user));
        } else if (profileData.avatarUrl && !authStore.user) {
            // 如果authStore.user是null但有头像数据，则设置整个user对象
            authStore.setUser({
                token: authStore.token, // 确保 token 也被传递
                user: {
                    ...profileData, // 包含所有 profileData
                    avatar: profileData.avatarUrl // 确保 avatar 属性被设置
                }
            });
        }
        console.log('>>> 个人信息已更新:', profile.value);
    } catch (error) {
        ElMessage.error('获取个人信息失败！' + error.message);
        console.error('>>> 获取个人信息出错:', error);
    }
};

/**
 * 保存用户个人信息
*/
const saveProfile = async () => {
    console.log('>>> 尝试保存个人信息...');
    try {
        const message = await personalInfoService.updatePersonalInfo(profile.value);
        ElMessage.success(message || '个人信息更新成功！');
        fetchProfile(); // 保存成功后重新获取最新信息，这将再次同步到 authStore
    } catch (error) {
        ElMessage.error('更新个人信息失败！' + error.message);
        console.error('>>> 保存个人信息出错:', error);
    }
};

/**
 * 上传头像
 * @param {Object} options - El-upload 的自定义上传选项
*/
const uploadAvatar = async (options) => {
    console.log('>>> 尝试上传头像...');
    const formData = new FormData();
    formData.append('file', options.file);
    try {
        const avatarUrl = await personalInfoService.uploadAvatar(formData);
        profile.value.avatarUrl = avatarUrl;
        // 【关键修改】: 将上传成功的头像URL同步到authStore中
        if (authStore.user) {
            authStore.user.avatar = avatarUrl;
            // 同时更新 localStorage 中的用户数据
            localStorage.setItem('user', JSON.stringify(authStore.user));
        } else {
            // 如果 authStore.user 不存在，可能需要先创建一个基础用户对象
            authStore.setUser({
                token: authStore.token, // 确保 token 也被传递
                user: {
                    username: profile.value.username, // 假设 username 是可用的
                    avatar: avatarUrl
                }
            });
        }
        ElMessage.success('头像上传成功！');
        options.onSuccess({ success: true, data: avatarUrl });
    } catch (error) {
        options.onError(error);
        ElMessage.error('头像上传失败！' + error.message);
        console.error('>>> 上传头像出错:', error);
    }
};

/**
 * 头像上传成功后的回调（主要逻辑已在 uploadAvatar 中处理）
 * @param {Object} response - Upload successful response
 * @param {Object} uploadFile - Uploaded file object
*/
const handleAvatarSuccess = (response, uploadFile) => {
    // 逻辑大部分已在 uploadAvatar 中处理
};

/**
 * 头像上传前的校验
 * @param {File} rawFile - Original file object
 * @returns {boolean} - Whether upload is allowed
*/
const beforeAvatarUpload = (rawFile) => {
    const isJPGPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
    const isLt2M = rawFile.size / 1024 / 1024 < 2;

    if (!isJPGPNG) {
        ElMessage.error('头像图片只能是 JPG/PNG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('头像图片大小不能超过 2MB!');
    }
    return isJPGPNG && isLt2M;
};

/**
 * 跳转到人脸识别页面
*/
const goToFaceRecognition = () => {
    router.push({ name: 'TeacherFaceRecognition' });
};

// 组件挂载时执行
onMounted(() => {
    fetchProfile(); // 获取个人信息
});
</script>

<style scoped>
/* -------------------------------------- */
/* 个人中心卡片样式 (保持不变) */
/* -------------------------------------- */
.profile-card {
    max-width: 800px;
    margin: 40px auto;
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
    /* 更强的阴影效果 */
    background-image: linear-gradient(to right, #9d50bb 0%, #6552f9 100%);
    /* 卡片背景的紫色渐变 */
    border: none;
    overflow: hidden;
    /* 确保内部内容不会溢出圆角 */
    position: relative;
    /* 确保内部元素的透明度可以基于此背景 */
    z-index: 1;
    /* 确保卡片内容在流星之上 */
}

.card-header,
.profile-content {
    /* 使用半透明的白色，让卡片自身的紫色渐变透出 */
    background-color: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(8px);
    /* 增加毛玻璃效果，稍微加强 */
    -webkit-backdrop-filter: blur(8px);
    /* Safari 兼容 */
}

.card-header {
    padding: 20px 30px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
    display: flex;
    align-items: center;
    font-size: 22px;
    font-weight: 500;
    color: #ffffff;
    position: relative;
    z-index: 1;
}

.card-header .el-icon {
    margin-right: 12px;
    font-size: 26px;
    color: #ffffff;
}

.profile-content {
    padding: 30px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-bottom-left-radius: 15px;
    border-bottom-right-radius: 15px;
    position: relative;
    z-index: 1;
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 40px;
    position: relative;
    margin-top: -60px;
    /* 向上偏移，与头部重叠 */
    z-index: 2;
    /* 确保头像在头部和内容之上 */
}

.el-avatar {
    border: 5px solid rgba(255, 255, 255, 0.5);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
    transition: transform 0.3s ease, border-color 0.3s ease;
}

.el-avatar:hover {
    transform: translateY(-5px);
    border-color: rgba(255, 255, 255, 0.8);
}

/* 优化“更换头像”链接按钮 */
.change-avatar-button {
    background-image: linear-gradient(to right, #a7b7ff 0%, #ffabe1 100%); /* 更亮的蓝紫色渐变 */
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    text-fill-color: transparent;
    font-weight: 700; /* 字体更粗 */
    margin-top: 15px;
    padding: 0;
    height: auto;
    text-decoration: underline;
    transition: all 0.3s ease; /* 过渡效果应用于所有变化 */
}

.change-avatar-button:hover {
    background-image: linear-gradient(to right, #c1cfff 0%, #ffc0eb 100%); /* 悬停时渐变更亮 */
    text-shadow: 0 0 12px rgba(255, 255, 255, 0.9); /* 增加发光效果，更明显 */
    transform: translateY(-1px); /* 向上轻微浮动 */
}
.change-avatar-button:active {
    background-image: linear-gradient(to right, #93a6e6 0%, #e69acb 100%); /* 点击时渐变稍暗 */
    text-shadow: none;
    transform: translateY(0);
}


.profile-form {
    width: 100%;
    max-width: 500px;
}

.el-form-item {
    margin-bottom: 25px;
}

.el-form-item label {
    font-weight: 700; /* 字体加粗，更显眼 */
    color: #ffffff;
    /* 调整阴影使其更亮更明显 */
    text-shadow: 
        0 0 10px rgba(255, 255, 255, 1),   /* 最内层，白色，高强度发光 */
        0 0 20px rgba(255, 255, 255, 0.8), /* 中间层，稍弱发光 */
        0 0 30px rgba(255, 255, 255, 0.6); /* 最外层，更扩散的发光 */
}

/* 优化输入框样式 */
.el-input__inner {
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.4); /* 边框稍微明显一点 */
    background-color: rgba(255, 255, 255, 0.2) !important; /* 背景稍微实一点 */
    box-shadow: inset 0 1px 6px rgba(0, 0, 0, 0.25); /* 阴影更深一点 */
    color: #ffffff !important;
    padding-left: 15px; /* 增加内边距，让文本不贴边 */
    transition: all 0.3s ease;
}

.el-input.is-disabled .el-input__inner {
    background-color: rgba(255, 255, 255, 0.1) !important; /* 禁用状态背景 */
    cursor: not-allowed;
    -webkit-text-fill-color: rgba(255, 255, 255, 0.7) !important; /* 禁用状态文本颜色，确保可见性 */
    opacity: 1;
    box-shadow: none; /* 禁用状态移除阴影 */
}

.el-input__inner::placeholder {
    color: rgba(255, 255, 255, 0.8); /* 占位符颜色更亮 */
}

.el-input__inner:focus {
    border-color: rgba(255, 255, 255, 0.9); /* 聚焦时边框更亮 */
    box-shadow: 0 0 12px rgba(255, 255, 255, 0.6); /* 聚焦时发光效果更明显 */
    background-color: rgba(255, 255, 255, 0.3) !important; /* 聚焦时背景稍亮 */
}

/* 优化保存按钮 */
.el-button--primary {
    width: 100%;
    background-image: linear-gradient(to right, #ee0979 0%, #ff6a00 100%); /* 调整为更活泼的橙粉渐变 */
    border: none;
    border-radius: 8px;
    padding: 14px 20px;
    font-size: 18px;
    font-weight: 500;
    color: #ffffff;
    transition: all 0.3s ease;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3); /* 阴影更深 */
}

.el-button--primary:hover {
    background-image: linear-gradient(to right, #ff6a00 0%, #ee0979 100%); /* 悬停时渐变反转，增加动感 */
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4); /* 悬停时阴影更深 */
    transform: translateY(-3px); /* 悬停时上浮更多 */
}

.el-button--primary:active {
    transform: translateY(0); /* 点击时恢复原位 */
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); /* 点击时阴影变浅 */
}

/* 优化人脸识别按钮 (如果使用，请取消注释) */
.face-recognition-button {
    width: 100%;
    margin-top: 15px; /* 与保存按钮的间距 */
    background-image: linear-gradient(to right, #00c6ff 0%, #0072ff 100%); /* 调整为更清爽的蓝青渐变 */
    border: none;
    color: #ffffff;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.25);
    border-radius: 8px;
    padding: 14px 20px;
    font-size: 18px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.face-recognition-button:hover {
    background-image: linear-gradient(to right, #00d2ff 0%, #0088ff 100%); /* 悬停时渐变稍亮 */
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.35);
    transform: translateY(-3px);
}

.face-recognition-button:active {
    transform: translateY(0);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
</style>